import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../services/habit_provider.dart';
import '../models/habit.dart';
import '../utils/app_theme.dart';
import '../widgets/habit_item.dart';
import 'analytics_screen.dart';
import 'add_habit_screen.dart';
import 'habit_detail_screen.dart';
import 'profile_screen.dart';
import 'templates_screen.dart';
import 'community_screen.dart';

class DashboardScreen extends StatefulWidget {
  const DashboardScreen({super.key});

  @override
  State<DashboardScreen> createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {
  int _currentIndex = 0;
  
  @override
  void initState() {
    super.initState();
    // Load habits when dashboard initializes
    Future.microtask(() {
      Provider.of<HabitProvider>(context, listen: false).loadHabits();
    });
  }
  
  void _addHabit() {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => const AddHabitScreen()),
    );
  }
  
  void _viewHabitDetail(Habit habit) {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => HabitDetailScreen(habit: habit)),
    );
  }
  
  Widget _buildTodaySummary(HabitProvider habitProvider) {
    final completionPercentage = habitProvider.completionPercentage;
    final streak = habitProvider.currentStreak;
    
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(16),
      decoration: AppTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text('今日概览', style: AppTheme.subheadingStyle),
              Text(
                DateFormat('yyyy年MM月dd日').format(DateTime.now()),
                style: AppTheme.smallTextStyle,
              ),
            ],
          ),
          const SizedBox(height: 16),
          ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: LinearProgressIndicator(
              value: completionPercentage,
              minHeight: 10,
              backgroundColor: Colors.grey.withOpacity(0.2),
              valueColor: const AlwaysStoppedAnimation<Color>(AppTheme.accentColor),
            ),
          ),
          const SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '已完成：${habitProvider.completedHabitsCount}/${habitProvider.totalHabitsCount}',
                style: AppTheme.bodyStyle,
              ),
              Row(
                children: [
                  const Icon(Icons.local_fire_department, color: Colors.orange),
                  const SizedBox(width: 4),
                  Text('连续完成：$streak天', style: AppTheme.bodyStyle),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }
  
  Widget _buildHabitsList(HabitProvider habitProvider) {
    if (habitProvider.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }
    
    if (habitProvider.habits.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.list_alt, size: 64, color: Colors.grey),
            const SizedBox(height: 16),
            const Text('还没有习惯', style: AppTheme.subheadingStyle),
            const SizedBox(height: 8),
            const Text('点击 "+" 按钮添加您的第一个习惯', style: AppTheme.smallTextStyle),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: _addHabit,
              icon: const Icon(Icons.add),
              label: const Text('添加习惯'),
              style: AppTheme.primaryButtonStyle.copyWith(
                minimumSize: MaterialStateProperty.all(const Size(200, 50)),
              ),
            ),
          ],
        ),
      );
    }
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('今日习惯', style: AppTheme.subheadingStyle),
        const SizedBox(height: 12),
        ...habitProvider.habits.map((habit) => HabitItem(
          habit: habit,
          onToggle: () => habitProvider.toggleHabitCompletion(habit),
          onTap: () => _viewHabitDetail(habit),
        )),
      ],
    );
  }
  
  Widget _buildWeeklySummary() {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 16),
      padding: const EdgeInsets.all(16),
      decoration: AppTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('本周进度', style: AppTheme.subheadingStyle),
          const SizedBox(height: 16),
          Container(
            height: 150,
            alignment: Alignment.center,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.bar_chart, size: 48, color: AppTheme.primaryColor),
                const SizedBox(height: 8),
                const Text('每周习惯完成率', style: AppTheme.bodyStyle),
                const SizedBox(height: 8),
                TextButton(
                  onPressed: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(builder: (context) => const AnalyticsScreen()),
                    );
                  },
                  child: const Text('查看详细统计'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildMotivationalQuote() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(16),
      decoration: AppTheme.cardDecoration,
      child: Column(
        children: [
          const Text(
            '"坚持好习惯不是靠意志力，而是靠好的系统和环境设计。"',
            style: TextStyle(
              fontSize: 16,
              fontStyle: FontStyle.italic,
              color: AppTheme.textPrimaryColor,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 8),
          const Text(
            '— 詹姆斯·克利尔《原子习惯》',
            style: TextStyle(
              fontSize: 14,
              color: AppTheme.textSecondaryColor,
            ),
            textAlign: TextAlign.right,
          ),
        ],
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    final habitProvider = Provider.of<HabitProvider>(context);
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的习惯'),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: _addHabit,
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _buildTodaySummary(habitProvider),
            _buildHabitsList(habitProvider),
            _buildWeeklySummary(),
            _buildMotivationalQuote(),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          if (index != _currentIndex) {
            if (index == 0) {
              // Stay on dashboard
              setState(() {
                _currentIndex = index;
              });
            } else if (index == 1) {
              // Navigate to templates
              setState(() {
                _currentIndex = index;
              });
              Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => const TemplatesScreen()),
              ).then((_) => setState(() => _currentIndex = 0));
            } else if (index == 2) {
              // Navigate to analytics
              setState(() {
                _currentIndex = index;
              });
              Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => const AnalyticsScreen()),
              ).then((_) => setState(() => _currentIndex = 0));
            } else if (index == 3) {
              // Navigate to community
              setState(() {
                _currentIndex = index;
              });
              Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => const CommunityScreen()),
              ).then((_) => setState(() => _currentIndex = 0));
            } else if (index == 4) {
              // Navigate to profile
              setState(() {
                _currentIndex = index;
              });
              Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => const ProfileScreen()),
              ).then((_) => setState(() => _currentIndex = 0));
            }
          }
        },
        type: BottomNavigationBarType.fixed,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.list_alt),
            label: '模板',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.bar_chart),
            label: '统计',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.people),
            label: '社区',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: '我的',
          ),
        ],
      ),
    );
  }
}
